package com.cat.at.chat.controller;

import com.cat.at.chat.component.SparkAiClient;
import com.cat.at.chat.config.SparkAIConfig;
import com.cat.at.chat.domain.SparkRequestDTO;
import com.cat.at.chat.domain.SparkResponseDTO;
import com.cat.at.chat.listener.SparkAIWebSocketListener;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {


    @Autowired
    private SparkAiClient client;


    @GetMapping("/singleChat")
    public String singleChat(String message) throws Exception {

        SparkAIWebSocketListener listener = new SparkAIWebSocketListener();

        SparkRequestDTO.MessageText messageText = new SparkRequestDTO.MessageText("user", message);


        WebSocket webSocket = client.sendToMessage("5597104", Arrays.asList(messageText), listener);
        try {
            int count = 0;
            // 为了避免死循环，设置循环次数来定义超时时长
            int maxCount = 500;
            while (count <= maxCount) {
                Thread.sleep(200);
                if (listener.isWsCloseFlag()) {
                    break;
                }
                count++;
            }
            if (count > maxCount) {
                return "大模型响应超时，请联系管理员";
            }
            // 响应大模型的答案
            return listener.getAnswer().toString();
        } catch (InterruptedException e) {
            log.error("错误：" + e.getMessage());
            return "系统内部错误，请联系管理员";
        } finally {
            // 关闭 websocket 连接
            webSocket.close(1000, "");
        }
    }


}
